import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import type { ApiResult } from '@/api/types'

const service = axios.create({
  baseURL: 'http://localhost:3005',
  timeout: 100000,
})

// @ts-ignore
service.interceptors.request.use((config: AxiosRequestConfig) => {
  if (config.headers)
    config.headers.Authorization = 'Bearer '
  return config
})

service.interceptors.response.use(
  (response: AxiosResponse) => {
    return Promise.resolve(response)
  }, (error) => {
    return Promise.reject(error)
  },
)

export function get<T>(url: string, params?: object, axiosConfig?: AxiosRequestConfig): Promise<ApiResult<T>> {
  const config: AxiosRequestConfig = {}
  if (axiosConfig) {
    Object.keys(axiosConfig).forEach((key) => {
      config[key as keyof AxiosRequestConfig] = axiosConfig[key as keyof AxiosRequestConfig]
    })
  }
  config.params = params
  return new Promise((resolve, reject) => {
    service.get(url, config).then((res) => {
      resolve(res.data)
    }).catch((err) => {
      reject(new Error(err))
    })
  })
}

export function post<T>(url: string, params?: object | string, axiosConfig?: AxiosRequestConfig): Promise<ApiResult<T>> {
  const config: AxiosRequestConfig = {}
  if (axiosConfig) {
    Object.keys(axiosConfig).forEach((key) => {
      config[key as keyof AxiosRequestConfig] = axiosConfig[key as keyof AxiosRequestConfig]
    })
  }
  return new Promise((resolve, reject) => {
    service.post(url, params, config).then((res) => {
      resolve(res.data)
    }).catch((err) => {
      reject(new Error(err))
    })
  })
}
